<script setup lang="ts">
import { ref, onMounted, computed } from "vue";
import * as echart from "echarts";
import { ElSelect, ElOption, ElCheckbox } from "element-plus";
import { useCurrentData } from "@/store/processFlow"
import { useElementSize,watchDebounced  } from "@vueuse/core"
import { get } from "lodash-es"

const props = defineProps<{title:string,name:string}>();
const currentData = useCurrentData();
const echartRef = ref<HTMLDivElement | undefined>();
//
const chartSelectData = ref<string[]>([]);

// const getData = () => {
//   let base = +new Date(2023, 8, 31);
//   // let oneDay = 24 * 3600 * 1000;
//   let onMin = 1000 * 60;
//   let data = [[base, Math.random() * 300]];
//   for (let i = 1; i < 200; i++) {
//     let now = new Date((base += onMin));
//     data.push([+now, Math.round((Math.random() * 1000 - 10))]);
//   }
//   return data;
// };
const getSeries = (c: string) => {
  return {
    type: "line",
    showSymbol: false,
    itemStyle:{
      color:c,
    },
    lineStyle: {
      color: c,
    },
    areaStyle: {
      color: {
        type: "linear",
        x: 0,
        y: 0,
        x2: 0,
        y2: 1,
        colorStops: [
          {
            offset: 0,
            color: c + "55", // 0% 处的颜色
          },
          {
            offset: 1,
            color: c + "00", // 100% 处的颜色
          },
        ],
        global: false, // 缺省为 false
      },
    },
  };
};

const colors = [
  "#FEA834",
  "#3B92FF",
  "#5470c6",
  "#91cc75",
  "#fac858",
  "#ee6666",
  "#73c0de",
  "#3ba272",
  "#fc8452",
  "#9a60b4",
  "#ea7ccc",
];

const ops = {
  tooltip: {
    trigger: "axis",
    formatter:(params:any) => `
      <b text-12 c="#333">${new Date(params[0].axisValue).toLocaleString().replace(/\//g,'-')}</b> <br />
      ${params.map((d:any) => `
        <div flex items-center p-y-2>
          <svg xmlns="http://www.w3.org/2000/svg" viewBox="5 5.8 4 2.4" width="24px">
            <path d="M 5 7 L 6 7 A 1 1 0 0 0 8 7 A 1 1 0 0 0 6 7 M 8 7 L 9 7" stroke="${d.color}" stroke-width="0.4" fill="none"/>
          </svg>
          <b fw-400 ml-4 text-12 c="#333333D9">${d.seriesName} : ${d.value[1]}</b>
        </div>
        
        `).join('')}
    `,
    axisPointer: {
      // 坐标轴指示器，坐标轴触发有效
      type: "line", // 默认为直线，可选为：'line' | 'shadow'
      crossStyle: {
        color: "#1D3C2B",
      },
    },
    // alwaysShowContent: true,
    className: "panel-chart-tooltip",
  },
  // legend:{zlevel:111},
  xAxis: {
    type: "time",
    boundaryGap: false,
    // minInterval:60 * 1000,
    interval:100
  },
  yAxis: {
    type: "value",
    // boundaryGap: [0, "100%"],
  },
  grid: { top: 10, bottom: 50 },
  dataZoom: [
    {
      startValue: new Date().getTime() - 300000,
      endValue: new Date().getTime(),
      height: 10,
      bottom: 10,
      moveHandleSize: 0,
      borderColor: "rgba(225,231,228,0.6)", // 组件边框的颜色
      fillerColor: "rgba(43,122,79,0.2)", // 滑动的填充色
      backgroundColor: "rgba(227,245,236,0.5)", // 背景色
    },
  ],
  series:[]
};

const mychart = computed(() => {
  if (echartRef.value) {
    let e = echart.init(echartRef.value);
    e.setOption(ops);
    return e;
  }
  return null;
});


const options = computed<{label:string,value:string}[]>(() => currentData.nodesList)

//
const id = computed(() => currentData.activeItem.id)

const chartData = computed(() => currentData.nodesChartData)
//
const sourceSeriesData = computed(() => {
  const k = id.value;
  const d:any = chartData.value;
  const td:any[] = d[k] || []
  return td.map(t => [t.timestamp,get(t.statusMetrics,props.name) || 0]) || []
})
//
const refreshChart = () => {
  const k = props.name;
  const ids = chartSelectData.value;
  const series:any[] = [];
  // 追加数据
  series.push({...getSeries("#2B7A4F"),name:currentData.activeItemName,data:sourceSeriesData.value})
  //
  for(let i = 0,l = ids.length; i < l;i++){
    const id = ids[i]
    const d:any[] = chartData.value[id] || [];
    const data:any[] = d.map((t) => [t.timestamp,get(t.statusMetrics,k) || 0])
    const name = options.value.filter(d => d.value == id)[0].label;
    //
    const c = colors[i]
    series.push({...getSeries(c),name,data})
  }
  //
  mychart.value?.setOption({series})
}

//
const chartContainer = ref<HTMLDivElement | null>(null)
const {width} = useElementSize(chartContainer)
watchDebounced(width,() => {mychart.value?.resize()},{ debounce: 500, maxWait: 1000 })
watchDebounced(chartSelectData,(v) => {
  console.log('++++++++',v)
  currentData.updateChartData(v)
},{ debounce: 500, maxWait: 1000 })
watchDebounced(chartData,() => {
  console.log('------------------------')
  refreshChart();
},{ debounce: 500, maxWait: 1000,deep:true })

onMounted(() => {
  refreshChart();
});
</script>

<template>
  <div
    ref="chartContainer"
    class="shadow-panel-2"
    flex-1
    box-border
    p-16
    h-full
    rd-4
    b="1px solid #E1E7E4"
  >
    <div w-full h-24 flex justify-between items-center relative>
      <i b-r="3px solid #2B7A4F" h-12 absolute top-6 left--17 rd-r-2></i>
      <span w="45%" truncate fw-600 c="#1D3C2B" text-12>{{ title || '测试 Name' }}</span>
      <el-select
        w="50%"
        v-model="chartSelectData"
        size="small"
        multiple
        class="no-tag-del"
        placeholder=""
        popper-class="chart-select-popper"
      >
        <el-option
          v-for="item in options"
          :key="item.value"
          :value="item.value"
          :label="item.label"
        >
          <p w-full h-full flex items-center h-24 text-12>
            <el-checkbox
              size="small"
              :model-value="chartSelectData.includes(item.value)"
            ></el-checkbox>
            <span ml-4 h-12 lh-12>{{ item.label }}</span>
          </p>
        </el-option>
      </el-select>
    </div>
    <div w-full box-border pt-8 class="_echart-container">
      <div ref="echartRef" w-full h-full></div>
    </div>
  </div>
</template>

<style scoped lang="scss">
._echart-container {
  height: calc(100% - 24px);
}
</style>

<style lang="scss">
.panel-chart-tooltip {
  background: rgba(255, 255, 255, 0.7) !important;
  backdrop-filter: blur(5px);
  box-shadow: 0px 8px 16px 0px rgba(29, 60, 43, 0.3) !important;
  border:none !important;
  padding:8px !important;
  display:none;
}

.chart-select-popper{
  background:#fff;
  .el-select-dropdown__list{
    .el-select-dropdown__item{
      height:24px;
      line-height:24px;
    }
  }
}
</style>
